﻿using EquipmentAlarmSystem.Service.Library;
using EquipmentAlarmSystem.Service.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace EquipmentAlarmSystem.Controllers;

public class SystemConfigurationController : Controller
{
    [Authorize]
    public IActionResult SystemSettings([FromForm] Configure configure)
    {
        if (configure.SamplingInterval == 0 && configure.PushInterval == 0)
        {
            return View(Basics.Config);
        }

        Basics.Config.SamplingInterval = configure.SamplingInterval;
        Basics.Config.PushInterval = configure.PushInterval;
        Basics.Config.EnablePush = configure.EnablePush;
        Basics.Config.Autograph = configure.Autograph;
        Basics.Config.Heartbeat = configure.Heartbeat;
        Basics.Config.EnableAlarmPush = configure.EnableAlarmPush;
        Basics.Config.EnableAlarmPushTime = configure.EnableAlarmPushTime;
        Basics.Config.DisableAlarmPushTime = configure.DisableAlarmPushTime;
        Basics.Config.ServiceType = configure.ServiceType;
        Basics.Config.ServiceAddress = configure.ServiceAddress;
        Basics.WriteConfig();

        return View(Basics.Config);
    }

    [Authorize]
    public IActionResult Contacts([FromForm] Contact contacts)
    {
        if (contacts.Name == null && contacts.PhoneNumber == null)
        {
            return View(Basics.Config);
        }
        List<string> Name = new();
        List<Contact> contacts1 = new();
        //修改已存在数据
        foreach (var item in Basics.Config.Contacts)
        {
            if (item.Name == contacts.Name)
            {
                item.PhoneNumber = contacts.PhoneNumber;
                item.EnableSms = contacts.EnableSms;
                item.EnableDialing = contacts.EnableDialing;
                item.Level = contacts.Level;
            }
            Name.Add(item.Name);
        }
        //电话号码 小于4位移除数据
        if (contacts.PhoneNumber.Length < 4)
        {
            contacts1 = new();

            foreach (var item in Basics.Config.Contacts)
            {
                if (item.Name == contacts.Name)
                {
                    continue;
                }
                contacts1.Add(item);
            }
        }
        else
        {
            contacts1 = Basics.Config.Contacts;
        }
        //新建联系人
        if (Name.Contains(contacts.Name) == false)
        {
            contacts1.Add(contacts);
        }
        //更新数据
        Basics.Config.Contacts = contacts1;
        //数据写入
        Basics.WriteConfig();

        return View(Basics.Config);
    }
}
